<template>
  <xr-create :loading="loading" :title="title" @close="close" @save="saveClick">
    <create-sections title="基本信息">
      <wk-form
        ref="crmForm"
        :model="fieldForm"
        :rules="fieldRules"
        :field-from="fieldForm"
        :field-list="fieldList"
        label-position="top"
        @change="formChange"
      >
        <template slot-scope="{ data }">
          <xh-customer-address
            v-if="data && data.formType == 'map_address'"
            :value="fieldForm[data.field]"
            @value-change="otherChange($event, data)"
          />
        </template>
      </wk-form>
    </create-sections>
    <el-button
      v-if="action.type == 'save' && contactsSaveAuth"
      slot="footer"
      class="handle-button"
      type="primary"
      @click="debouncedSaveField(true)"
      >保存并新建联系人</el-button
    >
    <!-- 新建 -->
    <contacts-create
      v-if="contactsCreateShow"
      :action="contactsCreateAction"
      @close="close"
      @save-success="close"
    />
  </xr-create>
</template>

<script>
import { filedGetFieldAPI } from "@/api/crm/common";
import { crmCustomerSaveAPI } from "@/api/crm/customer";

import XrCreate from "@/components/XrCreate";
import CreateSections from "@/components/CreateSections";
import WkForm from "@/components/NewCom/WkForm";
import { XhCustomerAddress } from "@/components/CreateCom";

import crmTypeModel from "@/views/crm/model/crmTypeModel";
import CustomFieldsMixin from "@/mixins/CustomFields";
import ContactsCreate from "../contacts/Create";

import { debounce } from "throttle-debounce";
import { isEmpty } from "@/utils/types";
import { mapGetters } from "vuex";

export default {
  // 新建编辑
  name: "CustomerCreate",

  components: {
    XrCreate,
    CreateSections,
    WkForm,
    XhCustomerAddress,
    ContactsCreate,
  },

  mixins: [CustomFieldsMixin],

  props: {
    phone: String,
    action: {
      type: Object,
      default: () => {
        return {
          type: "save",
          id: "",
          data: {},
        };
      },
    },
  },

  data() {
    return {
      loading: false,
      baseFields: [],
      fieldList: [],
      fieldForm: {},
      fieldRules: {},
      contactsCreateAction: {
        type: "save",
        id: "",
        data: {},
      },
      contactsCreateShow: false,
    };
  },

  computed: {
    ...mapGetters(["crm"]),
    contactsSaveAuth() {
      return this.crm.contacts && this.crm.contacts.save;
    },
    title() {
      return this.action.type === "update" ? "编辑学员" : "新建学员";
    },
  },

  watch: {},

  created() {
    this.debouncedSaveField = debounce(300, this.saveClick);

    this.getField();
  },

  mounted() {},

  beforeDestroy() {},

  methods: {
    /**
     * 获取数据
     */
    getField() {
   
      this.loading = true;
      const params = {
        label: crmTypeModel.customer,
      };

      if (this.action.type == "update") {
        params.id = this.action.id;
      }

      filedGetFieldAPI(params)
        .then((res) => {
          const list = res.data || [];
          if (!isEmpty(this.phone)) {
            list.forEach((item) => {
              if (item.formType === "mobile") {
                item.defaultValue = this.phone;
              }
            });
          }

          const fieldList = [];
          const fieldRules = {};
          const fieldForm = {};
          list.forEach((item) => {
            const temp = {};
            temp.field = item.fieldName;
            temp.formType = item.formType;
            temp.restrictData = item.restrictData;
            temp.displayShow = true;
            if (item.formType === "select") {
              if (item.authLevel == 1) {
                temp.displayShow = false;
              } else {
                temp.displayShow = true;
              }
            }
            if (item.formType === "leve_linkage") {//多级下拉option
              temp.levelData = item.levelData;
            }
            temp.fieldId = item.fieldId;
            temp.inputTips = item.inputTips;
            temp.name = item.name;
            temp.setting = item.setting;
            if (item.fieldName === "telephone") {
              temp.maxlength = item.maxLength;
            }
            if (item.fieldName === "trainingPeriods") {
              temp.oninput = item.oninput;
              temp.maxlength = item.maxLength;
            }
            const canEdit = this.getItemIsCanEdit(item, this.action.type);
            // 是否能编辑权限
            if (canEdit) {
              fieldRules[temp.field] = this.getRules(item);
            }

            if(temp.formType == 'single_user'){
              // 人员选择 课程讲师
              if(temp.fieldId == 1102103){
                temp.isTeacher = true;
              }else{
                temp.isTeacher = false;
              }
            }

            // 是否可编辑
            temp.disabled = !canEdit;

            // 禁止某些业务组件选择
            if (temp.formType == "number_input") {
              if (this.action.type == "relative") {
                const relativeDisInfos = {
                  contacts: { customer: true },
                  customer: { customer: true },
                  business: { customer: true, business: true },
                };

                // 在哪个类型下添加
                const relativeTypeDisInfos =
                  relativeDisInfos[this.action.crmType];
                if (relativeTypeDisInfos) {
                  // 包含的字段值
                  temp.disabled = relativeTypeDisInfos[item.formType] || false;
                }
               
              } else if (this.action.type == "update") {
                temp.disabled = item.formType === "number_input";
              }
            }
            // 特殊字段允许多选
            this.getItemRadio(item, temp);

            // 获取默认值
            fieldForm[temp.field] = this.getItemValue(
              item,
              this.action.data,
              this.action.type
            );
            fieldList.push(temp);
          });

          this.baseFields = list;
          this.fieldList = fieldList;
          this.fieldForm = fieldForm;
          this.fieldRules = fieldRules;

          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 保存
     */
    saveClick(createContacts = false) {
      this.loading = true;
      const crmForm = this.$refs.crmForm.instance;
      crmForm.validate((valid) => {
        if (valid) {
          const params = this.getSubmiteParams(this.baseFields, this.fieldForm);
          this.submiteParams(params, createContacts);
        } else {
          this.loading = false;
          // 提示第一个error
          this.getFormErrorMessage(crmForm);
          return false;
        }
      });
    },

    /**
     * 提交上传
     */
    submiteParams(params, createContacts) {
      if (this.action.type == "update") {
        params.entity.customerId = this.action.id;
        params.entity.batchId = this.action.batchId;
      }

      // 相关添加时候的多余提交信息
      if (
        this.action.relativeData &&
        Object.keys(this.action.relativeData).length
      ) {
        params = { ...params, ...this.action.relativeData };
      }
      crmCustomerSaveAPI(params)
        .then((res) => {
          this.loading = false;
          this.$store.dispatch("GetMessageNum");

          if (createContacts) {
            this.contactsCreateAction = {
              type: "relative",
              crmType: "customer",
              data: {
                customer: res.data || {},
              },
            };
            this.contactsCreateShow = true;
          } else {
            this.$message.success(
              this.action.type == "update" ? "编辑成功" : "添加成功"
            );
            this.close();
          }

          // 保存成功
          this.$emit("save-success", {
            type: "customer",
            data: res.data || {},
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 验证唯一
     */
    UniquePromise({ field, value }) {
      return this.getUniquePromise(field, value, this.action);
    },

    /**
     * change
     */
    formChange(item, index, value, valueList) {},

    /**
     * 地址change
     */
    otherChange(data, field) {
      //           this.fieldList.forEach(fieldItem => {
      //           console.log(fieldItem, 111111111,data,this.fieldForm);
      //  if (fieldItem.fieldId == "1102038") {
      //               console.log(data.value,11111)
      //             let str =data.value.length>0?data.value[0].assistantUserId*1:''
      //             let arr = []
      //             if(str){
      //             arr.push(str)
      //             console.log(str,this.fieldForm)
      //             this.fieldForm.fliedNqgisi =arr
      //             }

      //           }
      //         })

      this.$set(this.fieldForm, field.field, data.value);
      this.$refs.crmForm.instance.validateField(field.field);
    },

    /**
     * 关闭
     */
    close() {
      this.contactsCreateShow = false;
      this.$emit("close");
    },
  },
};
</script>

<style lang="scss" scoped>
.wk-form {
  /deep/ .el-form-item.is-map_address {
    flex: 0 0 100%;
  }
}
</style>
